package com.minelx.statementsplus.cha.common;

import java.util.LinkedList;
import java.util.Stack;

public class NodeBuilder<E> {
	private final Stack<Node<E>> trace;

	public NodeBuilder(E root) {
		trace = new Stack<>();
		markAsCurrentNode(subNode(root));
	}

	public NodeBuilder<E> leaf(E leaf) {
		currentNode().children().add(Node.leaf(leaf));
		return this;
	}

	public NodeBuilder<E> sub(E sub) {
		Node<E> added = subNode(sub);
		currentNode().children().add(added);
		markAsCurrentNode(added);
		return this;
	}

	public NodeBuilder<E> back() {
		trace.pop();
		return this;
	}

	public Node<E> build() {
		return trace.lastElement();
	}

	private Node<E> currentNode() {
		return trace.peek();
	}

	private void markAsCurrentNode(Node<E> added) {
		trace.push(added);
	}

	private Node<E> subNode(E sub) {
		return new Node<>(sub, new LinkedList<>());
	}
}
